<template>
  <div id="container">
    Excel导入
    <a-button
      style="margin-left:16px;"
      type="primary"
      @click="closeExcel"
    >
      关闭
    </a-button>
    <a-spin
      :spinning="isParsing"
    >
      <div>
        <a-row type="flex" justify="space-around" align="middle">
          <a-col
            :span="4"
          >
            <a-upload :multiple="false" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
              <a-button> <a-icon type="upload" /> 选择文件 </a-button>
            </a-upload>
            <a-button
              type="primary"
              :disabled="fileList.length === 0"
              :loading="uploading"
              style="margin-top: 16px"
              @click="handleParseExcel"
            >
              {{ uploading ? '导入中' : '开始导入' }}
            </a-button>
            <!-- <a-button type="primary">上传Excel</a-button> -->
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-alert
              show-icon
              message="提示"
              v-if="alertVisible"
              :type="alertType"
              banner
            >
              <template slot="description">
                <span v-text="(alertType==='error') ? '有错误，请修正后再导入' : '匹配完成，请点击导入数据至服务器按钮！'"></span>
                <a-button v-if="(alertType==='success')" type="primary" @click="uploadData">导入数据至服务器</a-button>
                <div v-if="alertType==='error'">
                  <p v-for="(item, index) in errorList" :key="index">
                    第{{ item.rowPosition }}行处<span v-text="item.errorMsg"></span>
                  </p>
                </div>
              </template>
            </a-alert>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-table
              :pagination="false"
              :columns="tableHeader"
              :data-source="tableData"
              :row-key="(record, index) => index"
            >
              <template slot="pressTypeDisplay" slot-scope="text, record, index">
                <a-select v-model="record.pressType" @change="onPressTypeChange($event, index, record)">
                  <a-select-option v-for="(item, _index) in settingList" :key="_index" :value="item.id">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </template>
              <template slot="memberName" slot-scope="text, record, index">
                <a-select v-model="record.member" @change="onMemberChange($event, index, record)">
                  <a-select-option v-for="(item, _index) in memberList" :key="_index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </div>
    </a-spin>
  </div>
</template>

<script>
import XLSX from 'xlsx'
// import 'moment-timezone'
// import moment from 'moment-msdate'
import { getSettingLists, getMemberLists, addDeliveries } from '@/api/manage'
// const moment = require('moment/moment').default
export default {
  name: 'DeliveriesExcel',
  data () {
    return {
      alertVisible: false,
      alertType: 'success', // success, info, warning, error
      alertDescription: '',
      errorList: [],
      isParsing: false,
      allDataCount: 0,
      allComplete: false,
      tableHeader: [
        {
          title: '报刊种类',
          dataIndex: 'pressTypeDisplay',
          scopedSlots: { customRender: 'pressTypeDisplay' }
        },
        {
          title: '收订员',
          dataIndex: 'subScriptioner'
        },
        {
          title: '份数',
          dataIndex: 'subscriptionCount'
        },
        {
          title: '手机号',
          dataIndex: 'cellPhone'
        },
        {
          title: '地址',
          dataIndex: 'detailedAddress'
        },
        {
          title: '投递站',
          dataIndex: 'deliverStation'
        },
        {
          title: '投递段',
          dataIndex: 'deliverPart'
        },
        {
          title: '开始时间',
          dataIndex: 'startDate'
        },
        {
          title: '结束时间',
          dataIndex: 'endDate'
        },
        {
          title: '审核状态',
          dataIndex: 'SubmitState'
        },
        {
          title: '客户名称',
          dataIndex: 'memberName',
          scopedSlots: { customRender: 'memberName' }
        },
        {
          title: '关联客户',
          dataIndex: 'customerName'
        },
        {
          title: '门牌号',
          dataIndex: 'doorplate'
        }
      ],
      tableData: null,
      fileList: [],
      uploading: false,
      settingList: [],
      memberList: []
    }
  },
  created () {
    this.getSelectData()
  },
  methods: {
    async uploadData () {
      this.isParsing = true
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i]
        await addDeliveries(item).then(res => {
          console.log(res)
        })
      }
      this.isParsing = false
      this.$emit('complete')
    },
    rejectErrorListByIndex (index, type, record) {
      // 不要用forEach 会造成异步相关的问题
      for (let i = 0; i < this.errorList.length; i++) {
        const item = this.errorList[i]
        if (type === item.errorType && item.id === record.id) {
          console.log(i)
          this.errorList.splice(i, 1)
        }
      }
      if (this.errorList.length < 1) {
        this.alertType = 'success'
      }
    },
    onMemberChange (value, index, record) {
      console.log(index)
      console.log(this.tableData)
      this.tableData[index].member = value
      this.rejectErrorListByIndex(index, 'member', record)
      console.log(value)
      console.log(index)
    },
    onPressTypeChange (value, index, record) {
      this.tableData[index].pressType = value
      this.rejectErrorListByIndex(index, 'pressType', record)
      console.log(value)
      console.log(index)
    },
    getSelectData () {
      getSettingLists().then(res => {
        this.settingList = res.data
      })
      getMemberLists().then(res => {
        this.memberList = res.data
      })
    },
    closeExcel () {
      this.$emit('close')
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    formatDate (numb, format = '-') {
        const time = new Date((numb - 1) * 24 * 3600000 + 1)
        time.setYear(time.getFullYear() - 70)
        const year = time.getFullYear() + ''
        const month = time.getMonth() + 1 + ''
        const date = time.getDate() + ''
        if (format && format.length === 1) {
            return year + format + month + format + date
        }
        return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    async matchSetting () {
      // return
    },
    async handleParseExcel () {
      this.isParsing = true
      window.setInterval(() => {
        if (this.allDataCount === this.tableData.length) {
          this.isParsing = false
        }
      }, 500)
      const file = this.fileList[0]
      var reader = new FileReader()
      const _self = this
      reader.onload = async function (e) {
          var data = e.target.result
          var wb = XLSX.read(data, { type: 'binary' })
          // 取出第一个sheet
          const firstWorksheet = wb.Sheets[wb.SheetNames[0]]
          // 转换成json方便渲染
          const jsonArr = XLSX.utils.sheet_to_json(firstWorksheet, { header: 1 })
          const tempData = jsonArr.slice(1, jsonArr.length)
          _self.allDataCount = tempData.length
          _self.tableData = []
          console.log(_self.tableHeader)
          for (let index = 0; index < tempData.length; index++) {
            const item = tempData[index]
            const dataItem = {}
            dataItem.id = index
            for (let _index = 0; _index < item.length; _index++) {
              const _item = item[_index]
              console.log(_self.tableHeader[_index].dataIndex, _item)
              dataItem[_self.tableHeader[_index].dataIndex] = _item
              if (_index === 0) {
                // 匹配pressType报刊种类
                // await _self.matchSetting()
                await getSettingLists({ search: _item }).then(res => {
                  console.log(res)
                  if ((res.data && res.data.length > 0)) {
                    dataItem.pressType = res.data[0].id
                    return
                  }
                  dataItem.pressType = null
                  throw res
                  // dataItem.pressType = (res.data && res.data.length > 0) ? res.data[0].id : null
                }).catch(e => {
                  dataItem.pressType = null
                  _self.errorList.push({
                    id: index,
                    rowPosition: index + 1,
                    colPosition: _index + 1,
                    errorType: 'pressType',
                    errorMsg: '请重新选择报刊种类'
                  })
                })
              }
              if (_index === 7) {
                // start date || end date
                dataItem.startDate = _self.formatDate(_item)
              }
              if (_index === 8) {
                dataItem.endDate = _self.formatDate(_item)
              }
              if (_index === 10) {
                // 匹配member客户名称
                await getMemberLists({ search: _item }).then(res => {
                  console.log(res)
                  if ((res.data && res.data.length > 0)) {
                    dataItem.member = res.data[0].id
                    return
                  }
                  dataItem.member = null
                  throw res
                  // dataItem.member = (res.data && res.data.length > 0) ? res.data[0].id : null
                }).catch(e => {
                  dataItem.member = null
                  _self.errorList.push({
                    id: index,
                    rowPosition: index + 1,
                    colPosition: _index + 1,
                    errorType: 'member',
                    errorMsg: '请重新选择客户名称'
                  })
                })
              }
            }
            _self.tableData.push(dataItem)
          }
          console.log(_self.errorList)
          console.log(_self.tableData)
          console.log(jsonArr)
          console.log(wb)
          _self.alertVisible = true
          if (_self.errorList && _self.errorList.length < 1) {
            _self.alertType = 'success'
            return
          }
          _self.alertType = 'error'
      }
      reader.readAsBinaryString(file)
    },
    handleUpload () {
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  min-height: 100%;
}
</style>
